<template>
  <view class="device-list-container">
    <!-- 头部 -->
    <view class="header">
      <text class="title">搜索结果</text>
    </view>
    <scroll-view
      style="height: 80vh"
      scroll-y
      @:show-scrollbar="false"
      refresher-enabled
      @refresherrefresh="handleRefresh"
      :refresher-triggered="triggered"
    >
      <view class="device-list">
        <view
          v-for="device in devices"
          :key="device.deviceId"
          class="device-item"
        >
          <view class="device-info">
            <view class="device-icon">
              <image
                class="bluetooth-icon"
                src="../../assets/icons/icon.png"
              ></image>
            </view>
            <view class="device-details">
              <text class="device-name">{{ device.name }}</text>
              <text class="device-id">{{ device.deviceId }}</text>
              <text class="device-rssi">信号强度: {{ device.RSSI }}dBm</text>
            </view>
          </view>

          <button
            class="connect-btn"
            :class="{ connecting: connectingDevice === device.deviceId }"
            :disabled="connectingDevice === device.deviceId"
            @click="handleConnect(device)"
          >
            {{ connectingDevice === device.deviceId ? "连接中..." : "连接" }}
          </button>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="devices.length === 0 && !isScanning" class="empty-state">
        <view class="empty-icon">
          <text class="wifi-slash-icon">📵</text>
        </view>
        <text class="empty-text">未搜索到任何设备</text>
        <button class="retry-btn" @click="handleRefresh">重新搜索</button>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref } from "vue";
import {
  bluetoothManager,
  buildPacket,
  stringTo28Bytes,
  ab2hex,
} from "@/utils";
import { onUnload } from "@dcloudio/uni-app";
const connectingDevice = ref<string | null>(null);
const devices = ref(bluetoothManager.getDevices());

const isScanning = ref(bluetoothManager.getIsScanning());
const handleConnect = async (device: UniApp.BluetoothDeviceInfo) => {
  try {
    // 设置连接状态
    connectingDevice.value = device.deviceId;

    // 连接设备
    await bluetoothManager.createBLEConnection(device.deviceId);
    try {
      await uni.setBLEMTU({
        deviceId: device.deviceId,
        mtu: 100,
      });
    } finally {
      const services = await bluetoothManager.getBLEDeviceServices(
        device.deviceId
      );
      console.log(services);
      for (const service of services.services) {
        if (service.uuid.includes("FFF0")) {
          const characteristics =
            await bluetoothManager.getBLEDeviceCharacteristics(
              service.uuid,
              device.deviceId
            );
          for (const characteristic of characteristics.characteristics) {
            if (characteristic.properties.notify) {
              await bluetoothManager.notifyBLECharacteristicValueChange(
                service.uuid,
                characteristic.uuid,
                true,
                device.deviceId
              );
              bluetoothManager.onBLECharacteristicValueChange(async (res) => {
                const deviceInfo = ab2hex(res.value as unknown as ArrayBuffer);
                // 每2位截取
                const [, , command, status] = deviceInfo.match(/.{1,2}/g) ?? [];
                console.log(deviceInfo, "deviceInfo");
                console.log(command, status);
                if (command === "06" && status === "00") {
                  // 跳转到配置选择页面
                  uni.navigateTo({
                    url: `/pages/config-selection/config-selection`,
                  });
                  uni.setStorageSync("deviceInfo", deviceInfo);
                  uni.showToast({
                    title: "设备已连接",
                    icon: "success",
                  });
                  const callback = (res) => {
                    if (!res.connected) {
                      uni.showToast({
                        title: "蓝牙已断开",
                        icon: "error",
                      });
                      uni.reLaunch({
                        url: `/pages/device-list/device-list`,
                      });
                      bluetoothManager.offBLEConnectionStateChange(callback);
                    }
                  };
                  bluetoothManager.offBLEConnectionStateChange(callback);
                  uni.offBLEConnectionStateChange();
                } else if (command === "02") {
                  hideLoading();
                } else if (command === "04") {
                  hideLoading();
                }
                if (status === "02") {
                  uni.showToast({
                    title: "指令执行失败",
                    icon: "none",
                  });
                  hideLoading();
                }
              });
            } else if (characteristic.properties.write) {
              const openId = uni.getStorageSync("openId");
              bluetoothManager.serviceId = service.uuid;
              bluetoothManager.characteristicId = characteristic.uuid;
              // const packet = buildPacket(0x07, [0x01]);
              // await bluetoothManager.sendPacket(
              //   bluetoothManager.serviceId,
              //   bluetoothManager.characteristicId,
              //   packet
              // );
              const packet = buildPacket(0x05, stringTo28Bytes(openId));
              console.log(packet, "packet");
              
              await bluetoothManager.sendPacket(
                service.uuid,
                characteristic.uuid,
                packet,
                device.deviceId
              );
            }
          }
          return;
        }
      }
    }
  } catch (error: any) {
    console.error("[DeviceList] 连接设备失败:", error);
    bluetoothManager.closeBLEConnection();
    uni.showToast({
      title: error.message || "连接失败",
      icon: "none",
    });
  } finally {
    connectingDevice.value = null;
  }
};
const triggered = ref(false);

const handleRefresh = async () => {
  try {
    triggered.value = true;
    const currentDevices = await bluetoothManager.startScanning();
    devices.value = currentDevices;
  } catch (error: any) {
    console.error("[DeviceList] 刷新设备列表失败:", error);
    uni.showToast({
      title: "刷新失败，请重试",
      icon: "none",
    });
  } finally {
    triggered.value = false;
  }
};
const hideLoading = () => {
  setTimeout(() => {
    uni.hideLoading();
  }, 1000);
};
onUnload(() => {
  bluetoothManager.offBLECharacteristicValueChange();
  bluetoothManager.closeBLEConnection();
});
</script>

<style scoped>
.device-list-container {
  height: 100vh;
  padding: 24rpx;
  background: linear-gradient(to bottom, #e6ebff, #f8faff, #ffffff);
  box-sizing: border-box;
  padding-top: calc(env(safe-area-inset-top) + 24rpx);
  padding-bottom: calc(env(safe-area-inset-bottom) + 24rpx);
  padding-left: calc(env(safe-area-inset-left) + 24rpx);
  padding-right: calc(env(safe-area-inset-right) + 24rpx);
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 32rpx;
  gap: 20rpx;
}

.title {
  color: #2c3045;
  font-size: 32rpx;
  font-weight: bold;
}

.refresh-btn {
  background: none;
  border: none;
  border-width: 0;
}

.refresh-icon {
  font-size: 32rpx;
  color: #2c3045;
}

.device-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.device-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #ecedf4;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.device-item:hover {
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.15);
}

.device-info {
  display: flex;
  align-items: center;
}

.device-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  /* background-color: #2c3045; */
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.bluetooth-icon {
  color: white;
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
}

.device-details {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.device-name {
  color: #2c3045;
  font-size: 26rpx;
  font-weight: 500;
}

.device-id {
  color: #666;
  font-size: 20rpx;
}

.device-rssi {
  color: #999;
  font-size: 18rpx;
}

.connect-btn {
  padding: 12rpx 24rpx;
  border-radius: 32rpx;
  font-size: 24rpx;
  font-weight: 500;
  border: none;
  background-color: #2c3045;
  color: white;
  transition: all 0.3s ease;
  margin: 0;
}

.connect-btn.connecting {
  background-color: #999;
  cursor: not-allowed;
}

.connect-btn:not(.connecting):hover {
  opacity: 0.9;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 80rpx;
  text-align: center;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #ecedf4;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
}

.wifi-slash-icon {
  font-size: 36rpx;
  color: #2c3045;
}

.empty-text {
  color: #666;
  font-size: 26rpx;
  margin-bottom: 20rpx;
}

.retry-btn {
  padding: 12rpx 32rpx;
  background-color: #2c3045;
  color: white;
  border-radius: 32rpx;
  font-size: 24rpx;
  border: none;
}
</style>
